import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

const router =  new Router({
  routes: [
    {  //404 路由拦截
      path:"*",
      redirect:'/'
    },
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    }
  ]
})
//路由拦截
router.beforeEach((to,from,next)=>{
  if (to.meta.requireAuth) {
    if (localStorage.timestamp) {
      let timestamp = localStorage.timestamp;
      let now = new Date().getTime();
      let cha = now - timestamp;
      if (cha<(86400000*30)) { //时间戳未过期(过期时间为30天)
        next();
      }else { //时间戳已过期
        localStorage.removeItem("token");
        localStorage.removeItem("timestamp");
        next({
            path: '/',
            query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
        })
      }
    }else {
      next({
        path:'/',
        query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  }else {
    next();
  }
})
export default router;
